package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Category;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping("/catalog")
public class SearchProductController {
    @Autowired
    CatalogService catalogService;
    @Autowired
    HttpSession session;

    @GetMapping("/viewProductId")
    public String search( String keyword, Model model){
        List<Product> productList = catalogService.searchProductList(keyword);
        model.addAttribute("productList",productList);

        return "catalog/SearchProducts";
    }

    @PostMapping("/searchProducts")
    public String searchProduct(@RequestParam("keyword") String keyword, Model model){
        if(keyword.trim().equals("")){
            return "catalog/main";
        }

        List<Product> productList = catalogService.searchProductList(keyword);
        model.addAttribute("productList",productList);
        return "catalog/searchProducts";
    }

    @GetMapping("/findResultServlet")
    public void findResultServlet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String keyword = request.getParameter("keyword");
        List<Product> productList = catalogService.searchProductList(keyword);
        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();
        String res = "";
        for(int i=0; i<productList.size(); i++){
            if(i>0){
                res += "," + productList.get(i).getName();
            }else{
                res += productList.get(i).getName();
            }
        }
        out.write(res);
        out.flush();
        out.close();
    }
}